package edu.zust.zw.shop.service.impl;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import edu.zust.zw.shop.db.dao.ShopUserDomainMapper;
import edu.zust.zw.shop.db.dao.domain.ShopUserDomain;
import edu.zust.zw.shop.db.dao.domain.ShopUserDomainExample;
import edu.zust.zw.shop.service.LoginService;

@Service
public class LoginServiceImpl implements LoginService {

    private static final int COLUMN_NUM = 18; // 18个资料选项
    private static final int RETURN_SUCCESS = 1;
    
    @Autowired
    private ShopUserDomainMapper userMapper;
    
    @Override
    public boolean login(String userId, String loginPass, String key) {
        ShopUserDomain userDomain = userMapper.selectByPrimaryKey(userId);
        String checkLoginPass = userDomain.getPassword();
        if (!checkLoginPass.equals(loginPass)) {
            return false;
        }
        
        String  checkKey = DigestUtils.md5Hex(userDomain.getUserId() + checkLoginPass);
        if (!checkKey.equals(key)) {
            return false;
        }
        
        return true;
    }

    @Override
    public boolean add(String userId, String username, String email, String password) {
        if (null != userMapper.selectByPrimaryKey(userId)) {
            return false;
        }
        ShopUserDomain userDomain = new ShopUserDomain();
        userDomain.setUserId(userId);
        userDomain.setUsername(username);
        userDomain.setEmail(email);
        userDomain.setPassword(DigestUtils.md5Hex(password));
        userDomain.setCreateAt(System.currentTimeMillis());
        userDomain.setLastUpdateAt(System.currentTimeMillis());
        return RETURN_SUCCESS == userMapper.insertSelective(userDomain);
    }

    @Override
    public boolean checkAccount(String userId) {
        // TODO Auto-generated method stub
        if (null != userMapper.selectByPrimaryKey(userId)) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkUsername(String username) {
        // TODO Auto-generated method stub
        ShopUserDomainExample ex = new ShopUserDomainExample();
        ShopUserDomainExample.Criteria criteria = ex.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<ShopUserDomain> domainList =  userMapper.selectByExample(ex);
        if (null != domainList && !domainList.isEmpty()) {
            return false;
        }
        return true;
    }
}
